//
//  GMExercisesVC.m
//  Teecloud
//
//  Created by 小熊 on 2018/10/24.
//  Copyright © 2018年 小志. All rights reserved.
//

#import "GMExercisesVC.h"
#import "GMExamModel.h"
#import "GMSubjectsModel.h"
#import "GMExercisesCell.h"
#import "GMExerciseCardVC.h"
#import "GMCommentVC.h"
@interface GMExercisesVC ()<UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,UICollectionViewDelegate>

@property (nonatomic, strong) GMExamModel *baseModel;
@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) NSMutableArray *dataArr;

@property (nonatomic, strong) UIButton *timeBtn;
@property (nonatomic, strong) ZJTimeCountDown *countDown;

@property (nonatomic, strong) UIBarButtonItem *timeItem;
@property (nonatomic, strong) UIBarButtonItem *commentItem;
@property (nonatomic, strong) UIBarButtonItem *settingBtnItem;
@end

@implementation GMExercisesVC
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"在线练习";
    self.view.backgroundColor = kWhiteColor;
    if (@available(iOS 11.0, *)) {
        self.collectionView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
    [self.collectionView registerNib:[UINib nibWithNibName:@"GMExercisesCell" bundle:nil] forCellWithReuseIdentifier:@"GMExercisesCell"];
    _timeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_timeBtn setTitle:@"00:00:00" forState:UIControlStateNormal];
    _timeBtn.titleLabel.font = [UIFont systemFontOfSize:12];
    [_timeBtn sizeToFit];
    _timeItem = [[UIBarButtonItem alloc] initWithCustomView:_timeBtn];
    UIButton *commentBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [commentBtn addTarget:self action:@selector(commentBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [commentBtn setImage:[UIImage imageNamed:@"conment"] forState:UIControlStateNormal];
    [commentBtn sizeToFit];
    _commentItem = [[UIBarButtonItem alloc] initWithCustomView:commentBtn];
    UIButton *settingBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [settingBtn addTarget:self action:@selector(jumpToCard) forControlEvents:UIControlEventTouchUpInside];
    [settingBtn setImage:[UIImage imageNamed:@"sumbit"] forState:UIControlStateNormal];
    [settingBtn sizeToFit];
    _settingBtnItem = [[UIBarButtonItem alloc] initWithCustomView:settingBtn];
    _countDown = [[ZJTimeCountDown alloc] init];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveNotification:) name:@"GMExercisesVC" object:nil];
    if (kIsEmptyObject(self.fromType)) {
        [self getExaminationData];
    }else{
        [self getexersesData];
    }
    [self addLeftBarButtonWithImage:[UIImage imageNamed:@"left-white-64"] action:@selector(left_BarButtonItemAction)];

}
- (void)left_BarButtonItemAction {
    if (kIsEmptyString(self.typeStr)) {
        [self.navigationController popViewControllerAnimated:YES];
    }else{
        [self.navigationController popToRootViewControllerAnimated:YES];
    }
}
-(void)getexersesData{
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setValue:FROM_IOS forKey:@"from"];
    [dict setValue:[XGMArchiverTools cacheForKey:BUSIORGID] forKey:@"busiOrgId"];
    [dict setValue:[XGMArchiverTools cacheForKey:USER_UserId] forKey:@"userId"];
    [dict setValue:self.fromType forKey:@"fromType"];
    [dict setValue:self.resId forKey:@"resId"];
    
    [dict setValue:[XGMArchiverTools cacheForKey:USER_identifierNumber] forKey:@"loginFinger"];
   
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [HJNetwork HTTPWithMethod:HJRequestMethodPOST url:[NSString stringWithFormat:@"ajax-api.ashx?$c=TeeyunApp&$m=GetExamSubject&$v=%@",VERSION] parameters:dict cachePolicy:HJCachePolicyIgnoreCache callback:^(id responseObject, NSError *error) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        if (!error) {
            if ([[responseObject objectForKey:RESULT_NAME_Success] boolValue]) {
                GMExamModel *model = [GMExamModel mj_objectWithKeyValues:[responseObject objectForKey:RESULT_NAME_Data]];
                if (model.IsAllowRemark) {
                    self.navigationItem.rightBarButtonItems  = @[self.settingBtnItem,self.commentItem,self.timeItem];
                }else{
                    self.navigationItem.rightBarButtonItems  = @[self.settingBtnItem,self.timeItem];
                }
                for (GMSubjectsModel *subModel in model.Subjects) {
                    subModel.examId = model.Id;
                }
                kWeakObject(self)
                [self.countDown zj_timeCountUPWithSecondTime:model.UseTime completeBlock:^(NSInteger hour, NSInteger minute, NSInteger second) {
                    [weakself.timeBtn setTitle:[NSString stringWithFormat:@"%02ld:%02ld:%02ld",hour,minute,second] forState:UIControlStateNormal];
                }];
                
                self.baseModel = model;
                [self.dataArr removeAllObjects];
                [self.dataArr addObjectsFromArray:model.Subjects];
                [self.collectionView reloadData];
                if (kIsEmptyObject(model)) {
                    UIAlertController *alert  = [UIAlertController zj_alertControllerWithTitle:@"提示" message:@"已练习完所有题目，重新开始练习？" optionStyle:OptionStyleStyleOK_Cancel OkTitle:@"好的" cancelTitle:@"不了" okBlock:^{
                        [self getExaminationData];
                    } cancelBlock:^{
                        [self.navigationController popViewControllerAnimated:YES];
                    }];
                    [self presentViewController:alert animated:YES completion:nil];
                }
            }else{

                UIAlertController *alert  = [UIAlertController zj_alertControllerWithTitle:@"提示" message:[responseObject objectForKey:RESULT_NAME_Message] optionStyle:OptionStyleStyleOnlyOK OkTitle:@"好的" cancelTitle:@"不了" okBlock:^{
                    [self.navigationController popViewControllerAnimated:YES];
                } cancelBlock:^{
                    [self.navigationController popViewControllerAnimated:YES];
                }];
                [self presentViewController:alert animated:YES completion:nil];
            }
        }else{
            [MBProgressHUD showErrorOrSuc:@"网络出错" toView:self.view];
        }
    }];
}
// @selector(receiveNotification:)方法， 即受到通知之后的事件
- (void)receiveNotification:(NSNotification *)noti{
    GMSubjectsModel *subModel = [GMSubjectsModel mj_objectWithKeyValues:noti.object];
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:[subModel.SortNo integerValue]-1 inSection:0] atScrollPosition:(UICollectionViewScrollPositionRight) animated:YES];
    });
    
}
-(void)getExaminationData{
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setValue:FROM_IOS forKey:@"from"];
    [dict setValue:[XGMArchiverTools cacheForKey:BUSIORGID] forKey:@"busiOrgId"];
    [dict setValue:[XGMArchiverTools cacheForKey:USER_UserId] forKey:@"userId"];
    [dict setValue:[XGMArchiverTools cacheForKey:USER_identifierNumber] forKey:@"loginFinger"];
    [dict setValue:self.groupId forKey:@"groupId"];
    [dict setValue:@"1" forKey:@"fromType"];
    [dict setValue:self.resId forKey:@"resId"];
    [dict setValue:self.packId forKey:@"packId"];
    
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [HJNetwork HTTPWithMethod:HJRequestMethodPOST url:[NSString stringWithFormat:@"ajax-api.ashx?$c=TeeyunApp&$m=GetExamSubject&$v=%@",VERSION] parameters:dict cachePolicy:HJCachePolicyIgnoreCache callback:^(id responseObject, NSError *error) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        if (!error) {
            if ([[responseObject objectForKey:RESULT_NAME_Success] boolValue]) {
                GMExamModel *model = [GMExamModel mj_objectWithKeyValues:[responseObject objectForKey:RESULT_NAME_Data]];
                if (model.IsAllowRemark) {
                     self.navigationItem.rightBarButtonItems  = @[self.settingBtnItem,self.commentItem,self.timeItem];
                }else{
                     self.navigationItem.rightBarButtonItems  = @[self.settingBtnItem,self.timeItem];
                }
                for (GMSubjectsModel *subModel in model.Subjects) {
                    subModel.examId = model.Id;
                }
                kWeakObject(self)
                [self.countDown zj_timeCountUPWithSecondTime:model.UseTime completeBlock:^(NSInteger hour, NSInteger minute, NSInteger second) {
                     [weakself.timeBtn setTitle:[NSString stringWithFormat:@"%02ld:%02ld:%02ld",hour,minute,second] forState:UIControlStateNormal];
                }];
                
                self.baseModel = model;
                [self.dataArr removeAllObjects];
                [self.dataArr addObjectsFromArray:model.Subjects];
                [self.collectionView reloadData];
                if (kIsEmptyObject(model)) {
                    UIAlertController *alert  = [UIAlertController zj_alertControllerWithTitle:@"提示" message:@"已练习完所有题目，重新开始练习？" optionStyle:OptionStyleStyleOK_Cancel OkTitle:@"好的" cancelTitle:@"不了" okBlock:^{
                        [self getExaminationData];
                    } cancelBlock:^{
                        [self.navigationController popViewControllerAnimated:YES];
                    }];
                    [self presentViewController:alert animated:YES completion:nil];
                }
            }else{
                UIAlertController *alert  = [UIAlertController zj_alertControllerWithTitle:@"提示" message:[responseObject objectForKey:RESULT_NAME_Message] optionStyle:OptionStyleStyleOnlyOK OkTitle:@"好的" cancelTitle:@"不了" okBlock:^{
                    [self.navigationController popViewControllerAnimated:YES];
                } cancelBlock:^{
                    [self.navigationController popViewControllerAnimated:YES];
                }];
                [self presentViewController:alert animated:YES completion:nil];
            }
        }else{
            [MBProgressHUD showErrorOrSuc:@"网络错误" toView:self.view];
        }
    }];
}
-(NSMutableArray *)dataArr{
    if (!_dataArr) {
        _dataArr = [[NSMutableArray alloc] init];
    }
    return _dataArr;
}
-(UICollectionView *)collectionView{
    if (!_collectionView) {
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
        [layout setScrollDirection:UICollectionViewScrollDirectionHorizontal];
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, -35, DEVICE_WIDTH, self.view.frame.size.height) collectionViewLayout:layout];
        _collectionView.backgroundColor = [UIColor whiteColor];
        _collectionView.pagingEnabled = YES;
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.showsHorizontalScrollIndicator = NO;
        _collectionView.showsVerticalScrollIndicator = NO;
        [self.view addSubview:_collectionView];
    }
    return _collectionView;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.dataArr.count;
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    GMExercisesCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"GMExercisesCell" forIndexPath:indexPath];
    GMSubjectsModel *subModel = self.dataArr[indexPath.row];
    cell.model = subModel;
    cell.name = self.baseModel.Title;
    cell.index = indexPath.row+1;
    cell.total = self.baseModel.Count;
    /**下一题*/
    cell.nextBlock = ^() {
        dispatch_async(dispatch_get_main_queue(), ^{
            [collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:indexPath.row+1 inSection:0] atScrollPosition:(UICollectionViewScrollPositionRight) animated:YES];
        });
    };
    /**上一题*/
    cell.lastBlock = ^() {
        dispatch_async(dispatch_get_main_queue(), ^{
            [collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:indexPath.row-1 inSection:0] atScrollPosition:(UICollectionViewScrollPositionLeft) animated:YES];
        });
    };
    kWeakObject(self)
    /**提交所有答案*/
    cell.sumbitBlock = ^{
        [weakself jumpToCard];
    };
    return cell;
}
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    return UIEdgeInsetsMake(0, 0, 0, 0);
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    return CGSizeMake(self.view.frame.size.width, self.view.frame.size.height);
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    return 0;
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    return 0;
}
//评论
-(void)commentBtnClick{
    GMCommentVC *comment = [[GMCommentVC alloc] init];
    comment.resId = self.baseModel.ResId;
    [self.navigationController pushViewController:comment animated:YES];
}
//跳转到答题卡
-(void)jumpToCard{
    GMExerciseCardVC *vc = [[GMExerciseCardVC alloc] init];
    vc.baseModel = self.baseModel;
    [self.navigationController pushViewController:vc animated:YES];
}

-(void)dealloc{
    [_countDown zj_timeDestoryTimer];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
@end
